package com.spzx.auth.controller;

import com.spzx.auth.form.H5RegisterBody;
import com.spzx.auth.form.LoginBody;
import com.spzx.auth.service.H5UserService;
import com.spzx.auth.service.SysLoginService;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.utils.JwtUtils;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.security.auth.AuthUtil;
import com.spzx.common.security.service.TokenService;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.system.api.model.LoginUser;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "H5项目登录注册管理")
@RestController
@RequestMapping("/h5")
public class H5UserController {

    @Autowired
    private H5UserService h5UserService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public R<?> register(@RequestBody H5RegisterBody h5RegisterBody) {
        //调用H6UserService中注册的方法
        h5UserService.register(h5RegisterBody);
        return R.ok();
    }

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public R<?> login(@RequestBody LoginBody form) {
        // 用户登录
        LoginUser userInfo = h5UserService.login(form);
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @Operation(summary = "用户登出")
    @DeleteMapping("/logout")
    public R<?> logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

}
